package util;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import org.dom4j.Document;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

/**
 * Handles with xml files
 * 
 * @author tanjian
 * 
 */
public class XmlUtil {
	/**
	 * read XML and transfer to Document
	 */
	public static Document toDOM(String fileName) {
		Document doc = null;
		try {
			File inputXml = new File(fileName);
			SAXReader saxReader = new SAXReader();
			doc = saxReader.read(inputXml);

		} catch (Exception e) {
			e.printStackTrace();
		}

		return doc;
	}

	/**
	 * Write a DOM to xml
	 * 
	 * @param document
	 * @param filename
	 */
	public static void toXML(Document document, String filename) {
		try {
			XMLWriter output = new XMLWriter(new FileWriter(new File(filename)));
			output.write(document);
			output.close();
		} catch (IOException e) {
			System.out.println(e.getMessage());
		}

	}

	/**
	 * String content transfer to Document
	 */
	public static Document contentToDOM(String content) {
		Document doc = null;
		try {
			SAXReader saxReader = new SAXReader();
			doc = saxReader.read(content);

		} catch (Exception e) {
			e.printStackTrace();
		}

		return doc;
	}
}
